<template>
    <div class="content">
        <TableLayout form-title="">
            <div slot="form-title" class="table-title"></div>
            <el-form :model="formInline" ref="formInline" class="formInline" label-width="50px" 
            label-position="right"  slot="form">          
                <el-row :gutter="41">
                    <el-col :span="8">
                        <el-form-item label="省">
                            <province v-model="formInline.fProvinceId" 
                             @getProvinceName='getProvinceName'>
                            </province>
                        </el-form-item>
                    </el-col>
                    <el-col :span="8">
                        <el-form-item label="市">
                            <city v-model="formInline.fCityId" :province="formInline.fProvinceId"
                             @getCityName='getCityName'>
                             </city>
                        </el-form-item>
                    </el-col>
                    <el-col :span="8">
                        <el-form-item label="区县">
                            <region v-model="formInline.fAreaId" :city="formInline.fCityId" 
                             @getAreaName='getAreaName'></region>
                        </el-form-item>
                    </el-col>
                </el-row>
                <div class="top-line">
                    <el-button type="primary" @click="onSubmit('formInline')">查询</el-button>
                </div>
            </el-form>
        </TableLayout>
       <div class="total-sales" v-loading="loading1">
           <div class="current-item">
               <div class="total-row">
                   <p class="add-user">新增用户（今日）</p>
                   <p class="total-num">{{newAddNums}}</p>
                   <p class="compare" v-show="!(newAddNumsPercent1===null)">对比昨日 
                       <span class="percent" :class="{'minus':newAddNumsPercent1<0,'add':newAddNumsPercent1>0}">
                           {{newAddNumsPercent}}
                       </span>
                  </p>
               </div>
               <div class="total-row">
                   <p class="add-user">登录次数（今日）</p>
                   <p class="total-num">{{openNums}}</p>
                   <p class="compare" v-show="!(openNumsPercent1===null)">对比昨日 <span class="percent" 
                   :class="{'minus':openNumsPercent1<0,'add':openNumsPercent1>0}">{{openNumsPercent}}</span></p>
               </div>
                <div class="total-row">
                   <p class="add-user">活跃用户（昨日）</p>
                   <p class="total-num">{{liveUsers}}</p>
                   <p class="compare" v-show="!(liveUsersPercent1===null)">对比前日 <span class="percent" :class="{'minus':liveUsersPercent1<0,'add':liveUsersPercent1>0}">{{liveUsersPercent}}</span></p>
               </div>
           </div>
       </div>
        <div class="chart-sales total-sales"  v-loading="loading2">
            <div class="sales-title">
                <span class="tip"></span>
                <span>用户增长趋势图</span>
            </div>
            <div>
                <echartLine :echartInfor="userAddQuShi" id="ida" class="style-echart" width='100%'></echartLine>
            </div>
        </div>
         <div class="chart-sales total-sales"  v-loading="loading3">
            <div class="sales-title">
                <span class="tip"></span>
                <span>用户活跃趋势图</span>
                 <el-form :model="formInline">
                      <el-row :gutter="41">
                        <el-col :span="5" :offset="18">
                            <el-form-item label="">
                                <el-select v-model="formInline.type" placeholder="请选择" style="width:100%" @change="changeType">
                                    <el-option v-for="(item,index) in typeArr" :key="index" :label="item.typeName" 
                                    :value="item.typeId"> </el-option>
                                </el-select>
                            </el-form-item>
                        </el-col>
                      </el-row>
                 </el-form>
            </div>
            <div>
                <echartLine :echartInfor="echartInforUser" id="idb" width='100%'></echartLine>
            </div>
        </div>
        <div class="echart-pie">
            <div class="chart-sales total-sales pie-left"  v-loading="loading4">
                <div class="sales-title">
                    <span class="tip"></span>
                    <span>用户类型分布</span>
                    <span class="totle-span">{{'('+totle1+'人)'}}</span>
                </div>
                <div>
                    <echartPie :echartInfor="echartPieUser" id="idc"></echartPie>
                </div>
            </div>
            <div class="chart-sales total-sales"  v-loading="loading5">
                <div class="sales-title">
                    <span class="tip"></span>
                    <span>区域注册分布</span>
                    <span  class="totle-span">{{'('+totle2+'人)'}}</span>
                </div>
                <div>
                    <echartPie :echartInfor="echartPieArea" id="idd"></echartPie>
                </div>
            </div>
        </div>
    </div>
</template>

<script>
import TableLayout from 'components/TableLayout';
import { mapState, mapActions, mapGetters } from 'vuex';
import province from 'components/CascadeRegion/province';
import city from 'components/CascadeRegion/city';
import region from 'components/CascadeRegion/region';
import echartLine from 'components/echart/echartLine';
import echartPie from 'components/echart/echartPie';
import { countStartTimes, countUserType, countNewUser, countByArea, userGrowthTrend, countActiveUser, getDayGrowthTrend, getMonthGrowthTrend} from 'api/reportForms';
import moment from 'moment';
export default{
    name: 'totalTrendList',
    components: {TableLayout, province, city, region, echartLine, echartPie},
    data() {
        return {
            loading1: true,
            loading2: true,
            loading3: true,
            loading4: true,
            loading5: true,
            totle1: 0,
            totle2: 0,
            formInline: {// form表单数据
                fProvinceId: '',
                fAreaId: '',
                provinceName: '',
                cityName: '',
                areaName: '',
                fCityId: '',
                type: '', // 日活跃还是月活跃
                time: ''// 默认近30tian
            },
            newAddNums: '- -', // 新增用户（今日）
            newAddNumsPercent: '- -',
            newAddNumsPercent1: null,
            openNums: '- -', // 启动次数
            openNumsPercent: '- -',
            openNumsPercent1: null,
            liveUsers: '- -', // 活跃用户数
            liveUsersPercent: '- -',
            liveUsersPercent1: null,
            AnnounceList: [],
            loading: true,
            //  用户增长趋势图
            userAddQuShi: null,
             // 用户活跃趋势图
            echartInforUser: null,
            // 饼状图，用户类型分布
            echartPieUser: null,
            // 饼状图，区域注册分布
            echartPieArea: null,
            typeArr: [
                {
                    typeName: '日活跃用户趋势', typeId: ''
                },
                {
                    typeName: '月活跃用户趋势', typeId: '1'
                }
            ]
        }
    },
   
    computed: {
        ...mapState({
            config: state => state.config.table
        }),
        ...mapGetters([
            'uid'
        ])
    },
    // 初始化
    created() {
        this.newAddNum();// 新增用户
        this.openNum();// 启动次数
        this.liveUser();// 活跃用户数
        this.userType()// 用户类型分布
        this.areaLoginIn()// 区域注册
        this.userAddQuShis();// 用户增长趋势图
        this.userUpdateQuShis();// 用户活跃趋势图 默认日活
    },
    methods: {
        // 全局获取行数
        ...mapActions(['ChangePageSize']),
        getProvinceName(provinceName) {
            this.formInline.provinceName=provinceName;
        },
        getCityName(cityName) {
            this.formInline.cityName=cityName;
        },
        getAreaName(areaName) {
            this.formInline.areaName=areaName;
        }, 
        // 日活跃和月活跃 改变
        changeType() {
            this.userUpdateQuShis()
        },
        // 表单查询
        onSubmit() {
            this.newAddNum();// 新增用户
            this.openNum();// 启动次数
            this.liveUser();// 活跃用户数
            this.userAddQuShis();// 用户增长趋势图
            this.userUpdateQuShis();// 用户活跃趋势图
            this.userType()// 用户类型分布
            this.areaLoginIn()// 区域注册
        },
         // 新增用户 id=1
        newAddNum() {
            this.loading1=true;
            let provinceId=this.formInline.fProvinceId;
            let cityId=this.formInline.fCityId;
            let areaId=this.formInline.fAreaId;
            countNewUser(provinceId, cityId, areaId).then(res => {
                this.loading1 = false;
                this.newAddNums = res.data.content.newUser?res.data.content.newUser:'--';// （新增人数）
                // this.newAddNumsPercent1= res.data.content.userPercent===null?null:Number(res.data.content.userPercent);// 新增比
                // this.newAddNumsPercent = res.data.content.userPercent===null?null:res.data.content.userPercent;// 页面展示的新增比
                // “”时不展示，“0”展示0 其他正常展示
                var userPercent = res.data.content.userPercent;
                this.newAddNumsPercent1=userPercent=='0'?0:userPercent?Number(userPercent.replace(/%/, '')):null;
                this.newAddNumsPercent = userPercent===null?null:userPercent;// 页面展示的新增比
            }).catch(() => {
                this.loading1 = false;
            });
        },
        // openNums: '', // 次数  id=2
        openNum() {
            this.loading1=true;
            let provinceId=this.formInline.fProvinceId;
            let cityId=this.formInline.fCityId;
            let areaId=this.formInline.fAreaId;
            countStartTimes(provinceId, cityId, areaId).then(res => {
                this.loading1 = false;
                this.openNums = res.data.content.startNumber?res.data.content.startNumber:'--';// （新增人数）
                // this.openNumsPercent1= res.data.content.percentage?Number(res.data.content.percentage):null;// 新增比
                var percentage = res.data.content.percentage;
                this.openNumsPercent1=percentage=='0'?0:percentage?Number(percentage.replace(/%/, '')):null;
                this.openNumsPercent = res.data.content.percentage===null?null:res.data.content.percentage;// 页面展示的新增比
            }).catch(() => {
                this.loading1 = false;
            });
        },
        // liveUsers: '', // 活跃用户数 id=3
        liveUser() {
            this.loading1=true;
            let provinceId=this.formInline.fProvinceId;
            let cityId=this.formInline.fCityId;
            let areaId=this.formInline.fAreaId;
            countActiveUser(provinceId, cityId, areaId).then(res => {
                this.loading1 = false;
                this.liveUsers = res.data.content.userNumber?res.data.content.userNumber:'--';// （新增人数）
                // this.liveUsersPercent1= res.data.content.percentage?Number(res.data.content.percentage):null;// 新增比
                var percentage = res.data.content.percentage;
                this.liveUsersPercent1=percentage=='0'?0:percentage?Number(percentage.replace(/%/, '')):null;
                this.liveUsersPercent = res.data.content.percentage===null?null:res.data.content.percentage;// 页面展示的新增比
            }).catch(() => {
                this.loading1 = false;
            });
           
        },
        // 区域注册 id=6
        areaLoginIn() {
            this.loading5=true;
            let provinceId=this.formInline.fProvinceId;
            let cityId=this.formInline.fCityId;
            let areaId=this.formInline.fAreaId;
            countByArea(provinceId, cityId, areaId).then(res => {
                this.loading5=false;
                this.totle2 = 0 ;
                let legendList=[];
                let pieList=[];
                res.data.content.forEach(item => {
                    this.totle2 += Number(item.newUser);
                    legendList.push(item.name);
                    pieList.push({name: item.name, value: item.newUser})
                })
                this.echartPieArea={
                    id: 'idd',
                    width: '100%',
                    height: '300px',
                // 圆柱的背景颜色
                    colorList: ['#7BC0F2', '#2EC7C9', '#FFB980', '#B6A2DE', '#D87A80'],
                    legend: {// title
                        orient: 'vertical',
                        left: 'left',
                        data: legendList,
                        show: false
                    },
               // 接口返回数据
                    dataShowList: pieList
                }
                
            }).catch(() => {
                this.loading5=false;
            })
        },
        // 用户类型分布 id=6
        userType() {
            this.loading4=true;
            let provinceId=this.formInline.fProvinceId;
            let cityId=this.formInline.fCityId;
            let areaId=this.formInline.fAreaId;
            countUserType(provinceId, cityId, areaId).then(res => {
                this.loading4=false;
                this.totle1= res.data.content.newUser?res.data.content.newUser:0;
                let legendList=[];
                let pieList=[];
                let listContent=[];
                if (res.data.content.listCount) {
                    listContent=res.data.content.listCount
                } else {
                    listContent=[]
                }
                listContent.forEach(val => {
                    if (val.name) {
                        legendList.push(val.name)
                        pieList.push({value: val.number, name: val.name})
                    }
                })
                this.echartPieUser={
                    id: 'idc',
                    width: '100%',
                    height: '300px',
                // 圆柱的背景颜色
                    colorList: ['#7BC0F2', '#2EC7C9', '#FFB980', '#B6A2DE', '#D87A80'],
                    legend: {// title
                        orient: 'vertical',
                        left: 'left',
                        data: legendList,
                        show: false
                    },
               // 接口返回数据
                    dataShowList: pieList
                }
            }).catch(() => {
                this.loading4=false;
            })
        },
   
        // 用户活跃趋势图 id=5
        userUpdateQuShis() {
            this.loading3=true;
            let currentDate=moment(new Date()).add(-1, 'days').format('YYYY-MM-DD');// 当前年月日
            let currentMonth=moment(new Date()).format('YYYY-MM-DD');// 当前月
            let beforeDate=moment(new Date()).add(-30, 'days').format('YYYY-MM-DD');// 近30天
            let beforeMonth=moment(new Date()).add(-1, 'year').format('YYYY-MM-DD');// 近12月
            let provinceId=this.formInline.fProvinceId;
            let cityId=this.formInline.fCityId;
            let areaId=this.formInline.fAreaId;
            let startTime= this.formInline.type==''?beforeDate:beforeMonth;// 按月查还是按天
            let endTime= this.formInline.type==''?currentDate:currentMonth;// 按月查还是按天
            if (!this.formInline.type) {// 日活
                this.getDayGrowthTrend(provinceId, cityId, areaId, startTime, endTime);
            } else {
                this.getMonthGrowthTrend(provinceId, cityId, areaId, startTime, endTime);// 月活
            }
           
        },
        // 用户增长趋势图 id=4
        userAddQuShis() {
            this.loading2=true;
            let provinceId=this.formInline.fProvinceId;
            let cityId=this.formInline.fCityId;
            let areaId=this.formInline.fAreaId;
            userGrowthTrend(provinceId, cityId, areaId).then(res => {
                this.loading2=false;
                let xAxisData=[];
                let dataList=[];
                res.data.content= res.data.content.reverse();
                res.data.content.forEach(val => {
                    xAxisData.push(val.date)
                    dataList.push(val.newUser)
                })
                this.userAddQuShi={
                    id: 'ida',
                    width: '100%',
                    height: '400px',
                         // 圆柱的背景颜色
                    colorList: ['rgb(164,205,238)'],
                    legend: {// title
                        data: ['用户增长']
                    },
                    xAxis: {// x轴
                        type: 'category',
                        data: xAxisData,
                        boundaryGap: false
                    },
                        // 接口返回数据
                    dataShowList: [
                        {
                            name: '用户增长',
                            data: dataList
                        }
                    ] 
                }
               
            }).catch(() => {
                this.loading2=false;
            })
        },
         //    日活还是月活
        dayOrMonth(res, name, legendData) {
            this.loading3=false;
            let xAxisData=[];
            let dataList=[{name, data: []}];
            let gotList=res.data.content.reverse()
            gotList.forEach(val => {
                xAxisData.push(val.date)
                dataList[0].data.push(val.userNumber)
            })
            this.echartInforUser={
                id: 'idb',
                width: '100%',
                height: '400px',
                // 圆柱的背景颜色
                colorList: ['rgb(164,205,238)', 'rgb(42,170,227)', 'rgb(25,46,94)', 'rgb(195,229,235)', 'rgb(222,222,222)'],
                legend: {// title
                    data: legendData
                },
                xAxis: {// x轴
                    type: 'category',
                    data: xAxisData,
                    boundaryGap: false
                },
               // 接口返回数据
                dataShowList: dataList
            }
        },
         // 日活
        getDayGrowthTrend(provinceId, cityId, areaId, startTime, endTime) {
            getDayGrowthTrend(provinceId, cityId, areaId, startTime, endTime).then(res => {
                let name='日活跃用户趋势';
                let legendData=['日活跃用户趋势'];
                this.dayOrMonth(res, name, legendData);
            }).catch(() => {
                this.loading3=false;
            })
        },
    //    月活
        getMonthGrowthTrend(provinceId, cityId, areaId, startTime, endTime) {
            getMonthGrowthTrend(provinceId, cityId, areaId, startTime, endTime).then(res => {
                let name='月活跃用户趋势';
                let legendData=['月活跃用户趋势'];
                this.dayOrMonth(res, name, legendData);
            }).catch(() => {
                this.loading3=false;
            })
        }
    }
}
</script>
<style lang="scss" scoped>
.style-echart{
     width: 100%;
     height: 400px;
}
.totle-span{
    display: inline-block;
    text-indent: 4px;

}
.content {
    position: relative;
    padding: 0px;
    $bgcolor:#fff;
    @mixin box-item() {
    overflow: hidden;
    background: $bgcolor;
    box-shadow: 0px 0px 5px 0px rgba(0, 0, 0, 0.1);
    -webkit-box-shadow: 0px 0px 5px 0px rgba(0, 0, 0, 0.1);
    color: #333;
    font-size: 14px;
    padding: 20px 20px;
  }
   .total-sales {
    @include box-item();
    }
    .current-item  {
      display: flex;
      justify-content: space-between;
      padding: 20px;
        .total-row{
            min-width: 300px;
            p{
                text-align: center;
            }
            .add-user{
                height: 36px;
                font-size: 18px;
                line-height: 36px;
                letter-spacing: 0px;
                color: #666666;
                
            }
            .total-num{
                height: 36px;
                font-size: 36px;
                line-height: 36px;
                letter-spacing: 0px;
                color: #212121;
            }
            .compare{
                height: 12px;
                font-size: 14px;
                line-height: 36px;
                letter-spacing: 0px;
                color: #999999;
                span{
                   color:#333;
                   display:inline-block;
                   text-indent: 16px;
                   width:80px;
                   text-align: left;
                }
                .minus{
                   color: #ff5722;
                }
                .add{
                     color:#2196f3
                }
            }
        }
        
    }
    .echart-pie{
      display: flex;
      justify-content: space-between;
      .total-sales{
          width: 50%;
      }
      .pie-left{
          margin-right:20px;
      }
    }
    .chart-sales{
            margin-top:20px;
    }
    .el-tag{
            margin-left:5px;
            background:#f9f9f9;
            color:#444;
        }
    .formInline {
        .formBtn{
            width: 100%;
            height: 70px;
            border-top: 1px solid #dddddd;
            position: relative;
            .btnPosition{
                position: absolute;
                right:0px; 
                top: 18px;
            }
        }
    }
     
}

</style>